<template>
  <el-dialog :title="title" v-model="visible" width="550px" destroy-on-close append-to-body :close-on-click-modal="false" @closed="$emit('closed')">
    <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="headers" :action="uploadUrl" :disabled="isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
      <el-icon style="font-size: 60px"><Upload /></el-icon>
      <div class="el-upload__text">将文件拖到此处，或<em style="margin-left: 3px;font-weight: bolder;">点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip">
          <el-row>
            <el-col :span="10">
              <el-checkbox v-model="updateSupport" style="margin-right: 5px;">
                <span style="font-size: 14px;">覆盖已存在的数据</span>
              </el-checkbox>
            </el-col>
            <el-col :span="14" v-if="updateSupport">
              <div style="float: right;">
                <el-select v-model="field" size="small" style="width: 120px;font-size: 14px;">
                  <el-option v-for="item in fieldList" value-key="prop" :key="item.prop" :label="item.label" :value="item.prop" />
                </el-select>
              </div>
              <div style="float: right;margin-right: 5px;margin-top: 3px;font-size: 14px;">更新标识</div>
            </el-col>
            <el-col :span="14" v-else>
              <div style="float: right;font-size: 14px;margin-top: 5px;">
                <span>仅允许导入xls、xlsx格式文件。</span>
                <el-link type="primary" :underline="false" style="font-size: 15px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
              </div>
            </el-col>
          </el-row>
          <!-- <div class="el-upload__tip" style="display: flex; align-items: center; justify-content: center">
            <el-checkbox v-model="updateSupport" style="margin-right: 5px" /> 是否更新已经存在的数据</div>
          <div class="el-upload__tip" style="text-align: center" v-if="updateSupport">更新标识是指选择哪个字段作为更新的依据。</div>
          <div v-if="updateSupport" class="el-upload__tip" style="display: flex; align-items: center; justify-content: center; margin-bottom: 7px">
            <div style="flex-shrink: 0; margin-right: 5px">更新标识</div>
            <el-select v-model="field" size="small">
              <el-option v-for="item in fieldList" value-key="prop" :key="item.prop" :label="item.label" :value="item.prop" />
            </el-select>
          </div>
          <div style="text-align: center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
          </div> -->
        </div>
      </template>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click.stop="submitFileForm">确 定</el-button>
        <el-button @click.stop="visible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
// import { ElLoading } from "element-plus"
import { Upload } from "@element-plus/icons-vue"
import { saveAs } from "file-saver"
import tool from "@/utils/tool"

export default {
  name: "FileUpload",
  components: {
    Upload
  },
  props: {
    upload: {
      type: Object,
      default() {
        return {}
      }
    },
    title: {
      type: String,
      default: "数据导入"
    },
    modelId: {
      type: [String, Number]
    },
    fieldList: {
      type: Array,
      default() {
        return []
      }
    }
  },
  computed: {
    uploadUrl() {
      let result = process.env.VUE_APP_API_URL
      if (this.updateSupport) {
        result = result + this.url + `&field=${this.field}&updateSupport=true`
      } else {
        result = result + this.url
      }
      return result
    }
  },
  data() {
    return {
      visible: false,
      updateSupport: false,
      isUploading: false,
      headers: {
        Authorization: tool.cookie.get("TOKEN")
      },
      url: `/system/model/import?modelId=${this.modelId}`,
      field: this.fieldList[0].prop
    }
  },
  methods: {
    // 打开dialog
    open() {
      this.visible = true
    },
    // 文件上传中处理
    handleFileUploadProgress() {
      this.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      this.visible = false
      this.isUploading = false
      this.updateSupport = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
      this.$emit("refresh")
    },
    // 模板下载
    importTemplate() {
      //   const downloadLoadingInstance = ElLoading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)" })
      this.$API.system.dataList.modelTemplate
        .get({ modelId: this.modelId }, { responseType: "blob" })
        .then((res) => {
          if (res.type !== "application/json") {
            const blob = new Blob([res])
            saveAs(blob, `导入模板_${new Date().getTime()}.xlsx`)
            this.$message.success({
              message: res.msg
            })
          } else {
            this.$message.error({
              message: res.msg
            })
          }

          //   downloadLoadingInstance.close()
        })
        .catch(() => {
          this.$message.error("下载文件出现错误，请联系管理员！")
          //   downloadLoadingInstance.close()
        })
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    }
  }
}
</script>

<style lang="scss" scoped>
:deep(.el-dialog__body) {
  padding-bottom: 0px !important;
}
:deep(.el-upload-dragger){
  border: 2px dotted #dcdfe6;
}
:deep(.el-upload-dragger:hover){
  border: 2px dotted #409eff;
}
</style>
